using System;
using System.Collections.Generic;
using System.Text;
using SlimDX;
using SlimDX.Direct3D9;
using Barrage.Global;

namespace Barrage.Textures
{
    /// <summary>
    /// Implements a singleton texture cache with autoload functions
    /// </summary>
    public class TextureManager : IDisposable
    {
        private static TextureManager instance=null;

        /// <summary>
        /// Returns the class instance.
        /// </summary>
        public static TextureManager Textures { get { if (instance == null) instance = new TextureManager(); return instance; } }

        private TextureManager() { 
            createDefaultTexture();
            Engine.RegisterDisposeHandler(new EngineDisposeHandler(Dispose));
        }
        private Dictionary<string, Texture> textures = new Dictionary<string, Texture>();

        private Texture defaultTexture;
        /// <summary>
        /// Returns the default texture (default.dds) that's loaded when loaded textures return error
        /// </summary>
        public static Texture DefaultTexture { get { return instance.defaultTexture; } }

        void createDefaultTexture(){
            defaultTexture = Texture.FromFile(Engine.Device, Store.PathConfig[Store.TEXTURE_PATH]+"default.dds");
        }

        /// <summary>
        /// Tries to load the texture with the specified name (in the TexturePath folder)
        /// </summary>
        /// <param name="name">texture name</param>
        /// <returns>If everything went well, the loaded texture. Else, the default texture</returns>
        public Texture this[string name]
        {
            get
            {
                Texture t=null;
                if (textures.TryGetValue(name,out t))
                    return t;
                NLog.LogManager.GetLogger(ToString()).Warn("Texture " + name + " not found. Trying to load");
                try
                {
                    t = Texture.FromFile(Barrage.Global.Engine.Device, Store.PathConfig[Store.TEXTURE_PATH]+name, Usage.None, Pool.Managed);
                    NLog.LogManager.GetLogger(ToString()).Debug("Texture " + name + " finished loading.");
                }
                catch{
                    NLog.LogManager.GetLogger(ToString()).Error("Error loading texture " + name);
                    t = DefaultTexture;
                }
                textures.Add(name, t);
                return t;
            }
        }

        /// <summary>
        /// Clear resources
        /// </summary>
        public void Dispose()
        {
            foreach (Texture t in textures.Values)
                if (t!=defaultTexture)
                    t.Dispose();

            defaultTexture.Dispose();
            defaultTexture = null; 
            textures.Clear();
            instance = null;
            NLog.LogManager.GetLogger(ToString()).Debug("Disposing");
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Creates a render target with the engine's window size and a X8R8G8B8 format
        /// </summary>
        /// <returns>A new render target</returns>
        public static Texture CreateSimpleRenderTarget()
        {
            return new Texture(Engine.Device, Engine.DefaultRenderTargetDescription.Width, Engine.DefaultRenderTargetDescription.Height, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Managed);
        }

        /// <summary>
        /// Loads the specified texture without adding it to the manager
        /// </summary>
        /// <param name="path">texture name</param>
        /// <returns>The loaded texture, or the default texture in case of error</returns>
        public static Texture LoadTexture(string path)
        {

            NLog.LogManager.GetCurrentClassLogger().Debug("Loading texture " + path);
            try
            {
                Texture t = Texture.FromFile(Barrage.Global.Engine.Device, path, Usage.None, Pool.Managed);
                NLog.LogManager.GetCurrentClassLogger().Debug("Texture " + path + " finished loading.");
                return t;
            }
            catch
            {
                NLog.LogManager.GetCurrentClassLogger().Error("Error loading texture " + path);
                return DefaultTexture;
            }
        }

        /// <summary>
        /// Destructor. Clear resources
        /// </summary>
        ~TextureManager()
        {
            Dispose();
        }
    }
}
